package com.baiyang.app.ui.mine.goods;

import android.content.Context;

import com.alibaba.fastjson.JSONObject;
import com.baiyang.app.tool.LogUtils;
import com.baiyang.app.tool.net.SendMsgUtil;
import com.baiyang.app.tool.net.Urls;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class GoodsService {

    private Context context;
    private GoodsViewModel viewModel;

    public GoodsService(Context context,GoodsViewModel viewModel){
        this.context = context;
        this.viewModel = viewModel;
    }

    public void getGoodsPage(int pageOn, String id) {
        JSONObject object = new JSONObject();
        object.put("pageOn",pageOn);
        object.put("orderBy","createTime");
        object.put("pageSize",10);
        JSONObject data = new JSONObject();
        data.put("del","0");
        data.put("available","1");
        object.put("data",data);
        new SendMsgUtil(){
            @Override
            public void deal(Call call, Response response) throws IOException {
                if(response.code() == 200){
                    String str = response.body().string();
                    LogUtils.i("goodsOperation/getPage",str);
                    viewModel.setGoods(JSONObject.parseObject(str));
                }else{
                    LogUtils.i("goodsOperation/getPage","code:" + response.code());
                }
            }
            @Override
            public void dealFailure(Call call, IOException e) throws IOException {
                LogUtils.i("goodsOperation/getPage","IOException:" + e.getLocalizedMessage());
            }
        }.sendPost(Urls.GOODS.GET_PAGE,object);
    }

    /**
     * 兑换
     */
    public void exchange(String goodsId, String userId,String phone,String address) {
        JSONObject object = new JSONObject();
        object.put("goodId",goodsId);
        object.put("userId",userId);
        object.put("phone",phone);
        object.put("address",address);
        new SendMsgUtil(){
            @Override
            public void deal(Call call, Response response) throws IOException {
                if(response.code() == 200){
                    String str = response.body().string();
                    LogUtils.i("goodsOperation/exchange",str);
                    viewModel.setExchangeResult(JSONObject.parseObject(str));
                }else{
                    LogUtils.i("goodsOperation/exchange","code:" + response.code());
                }
            }
            @Override
            public void dealFailure(Call call, IOException e) throws IOException {
                LogUtils.i("goodsOperation/exchange","IOException:" + e.getLocalizedMessage());
            }
        }.sendPost(Urls.EXCHANGE.EXCHANGE_CON,object);
    }
}
